//
//  XJHomeStatusViewModel.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/20.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class XJHomeStatusViewModel: NSObject {
    
    var statusArr:[XJHomeCellViewModel]?
    /**
     加载首页数据
     */
    func loadData(isPullup: Bool,finished: (isSuccess: Bool, count: Int)->()) {
        
        //let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var max_id: Int64 = 0
        var since_id: Int64 = 0
        if isPullup {
            
            //上拉取到当前数组最后一个元素
            max_id = statusArr?.last?.status?.id ?? 0
            
            if max_id != 0{
                
                max_id--
            }
        }else{
            //下拉刷新
            since_id = statusArr?.first?.status?.id ?? 0
        }
        
        XJStatusDAL.loadData(max_id, since_id: since_id) { (dicts) -> () in
            
            guard let res = dicts else{
                finished(isSuccess: false, count: 0)
                return
            }
            var tempArr = [XJHomeCellViewModel]()
            for values in res {
                
                let statusModel = XJHomeStatusModel(dict: values)
                let viewModel = XJHomeCellViewModel()
                viewModel.status = statusModel
                
                tempArr.append(viewModel)
            }
            // self.statusArr = tempArr
            
            if self.statusArr == nil {
                
                self.statusArr = [XJHomeCellViewModel]()
            }
            
            /**
            *  判断是否上拉
            */
            if isPullup{
                
                self.statusArr = self.statusArr! + tempArr
            }else{
                self.statusArr = tempArr + self.statusArr!
            }
            //用闭包通知控制器刷新数据
            //finished(isSuccess: true)
            self .cacheSingleImg(tempArr, finished: finished)
        }
        
    }
    

    /**
    *  缓存单张图片
    */

    private func cacheSingleImg(array: [XJHomeCellViewModel], finished: (isSuccess: Bool, count: Int)->()){
    
        let group = dispatch_group_create()
        
        //遍历数组,判断是否单张
        for value in array {
        
            let originalPicUrls = value.status?.pic_urls
            let retweetPicUrls = value.status?.retweeted_status?.pic_urls
            
            let picUrls = (originalPicUrls == nil || originalPicUrls?.count == 0) ? retweetPicUrls : originalPicUrls
            
            if picUrls?.count == 1 {
                //下载地址
                let urlStr = picUrls?.first?.thumbnail_pic
                
                dispatch_group_enter(group)
                //下载图片
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlStr ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                    //更新单张图片大小
                    value.updateSingeImgSize()
                    dispatch_group_leave(group)
                    
                })
            }
        }
        //所有单张图片下载完成通知
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            finished(isSuccess: true, count: array.count)
        }
    
    }
    
}

